<?php

class CE_Database {

	private static $databaseSettings = array(
		// Database Connection
		'default' =>  array(
			'host' => 'localhost',
			'username' => 'root',
			'password' => 'PUT YOUR PASSWORD HERE',
			'databaseName'=> 'arenablitz',
			'port' => 3306),
		);

	/**
	 * The static instances table is a cache of database connection objects.
	 * If a database object has already been created within this page context,
	 * the same object will be returned again.
	 * This is most useful for the 'default' database, which would otherwise
	 * be instantiated multiple times.
	 */
	private static $instances = array();


	/**
	 * The link is a reference to the open database connection.
	 */
	private $link;


	/**
	 * Gets an instance of the database class for a particular database type
	 * and object id.
	 * Database type refers to one of the preconfigured types in RIS_Config.
	 * Object id is used for sharding.  Not all database types use the id.
	 *
	 * @param name
	 * @param id
	 * @returns
	 */
	public static function getInstance($name = 'default', $id = '') {
		if (isset(self::$instances[$name])) {
			return self::$instances[$name];
		}

		$settings = self::$databaseSettings[$name];
		if (!$settings) {
			die('Unrecognized database configuration: ' . $name);
		}

		$db = new CE_Database($settings);
		self::$instances[$name] = $db;
		return $db;
	}


	/**
	 * Creates a new CE_Database object.
	 */
	function __construct($settings) {
		$db = $settings['host'] . ':' . $settings['port'];
		$un = $settings['username'];
		$pw = $settings['password'];

		$this->link = mysql_connect($db, $un, $pw);

		if (!$this->link) {
			die('Could not connect: ' . mysql_error());
		}

		$selected = mysql_select_db($settings['databaseName'], $this->link);

		if (!$selected) {
			die('Could not select: ' . mysql_error());
		}
	}


	/**
	 * Destroys the database object and closes the active connection.
	 */
	function __destruct() {
		mysql_close($this->link);
	}


	/**
	 * Escapes quotes and other special characters for safe SQL.
	 * All user provided strings should run through this method before execution.
	 *
	 * @param text
	 * @returns
	 */
	public function escape($text) {
		return mysql_real_escape_string($text, $this->link);
	}


	/**
	 * Executes a SQL query and returns a reference to the result set.
	 *
	 * @param sql
	 * @returns
	 */
	public function query($sql) {
		$result = mysql_query($sql, $this->link);

		if (!$result) {
			die('Error in SQL query: ' . $this->error());
		}

		return $result;
	}


	/**
	 * Fetches the next row for a result set.
	 * Returns FALSE if no more rows are available.
	 *
	 * @param result
	 * @returns
	 */
	public function fetch($result) {
		return mysql_fetch_array($result);
	}


	/**
	 * Frees a result set.
	 *
	 * @param result
	 */
	public function free($result) {
		mysql_free_result($result);
	}


	/**
	 * Gets an array of objects from the result of the SQL query.
	 * Object properties are based on the names of the SQL columns.
	 *
	 * @param sql
	 * @returns
	 */
	public function getObjectArray($sql) {
		$rs = mysql_query($sql, $this->link);

		if (!$rs) {
			die('Error in SQL query: ' . $this->error());
		}

		$fieldCount = mysql_num_fields($rs);
		$results = array();

		while ($row = mysql_fetch_array($rs)) {
			$obj = array();

			for ($i = 0; $i < $fieldCount; $i++) {
				$name = mysql_field_name($rs, $i);
				$obj[$name] = $row[$name];
			}

			$results[] = (object)$obj;
		}

		mysql_free_result($rs);

		return $results;
	}


	/**
	 * Get an objects from the result of the SQL query.
	 * Object properties are based on the names of the SQL columns.
	 *
	 * @param sql
	 */
	public function getObject($sql) {
		$array = $this->getObjectArray($sql);
		return $array[0];
	}


	/**
	 * Gets a single value from the given SQL query.
	 * Only looks at the first column from the first row.
	 *
	 * @param sql
	 * @returns
	 */
	public function getValue($sql) {
		$rs = mysql_query($sql, $this->link);

		if (!$rs) {
			die('Error in SQL query: ' . mysql_error());
		}

		$row = mysql_fetch_array($rs);

		if (!$row) {
			die('No results in SQL query.');
		}

		$result = $row[0];
		mysql_free_result($rs);
		return $result;
	}


	/**
	 * Gets the last insert ID.
	 *
	 * @returns
	 */
	public function getLastInsertID() {
		return mysql_insert_id($this->link);
	}


	/**
	 * Returns the last executed query error/ warning, returns FALSE if theres no error 
	 * @returns
	 */
	private function error() {
		return mysql_error();
	}
}

?>